class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        int left = 0, right = nums.length - 1, mid;

        // 比target小的后一个元素的下标
        while (left <= right){
            mid = left + ((right - left)>>1);
            if (nums[mid] < target){
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        res[0] = left;

        left = 0;
        right = nums.length - 1;
        // 比target大的前一个元素的下标
        while (left <= right){
            mid = left + ((right - left)>>1);
            if (nums[mid] <= target){
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        res[1] = right;
        if (res[0] <= res[1]){
            return res;
        } else {
            return new int[]{-1,-1};
        }
    }
}